﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ecommerce.Web.Code;
using Ecommerce.Model;
using Ecommerce.Frete;

namespace Ecommerce.Web
{
    public partial class SelecionarEndereco : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Carrinho.Instance.Frete.Equals(0))
            {
                Response.Redirect("~/CarrinhoCompras.aspx");
            }

            if (!IsPostBack)
            {
                this.DesabilitarForm();
                this.CarregarEnderecos();
                this.ctrlProgressoCheckout.CarregarDadosPedido();
                this.ctrlProgressoCheckout.MostrarDadosEndereco(false);
            }
        }

        private void CarregarEnderecos()
        {
            rbEnderecos.Items.Clear();

            List<tb_end_endereco> lista = EnderecoModel.Instance.ListarPorPessoa(this.IdentificadorUsuarioLogado);
            lista.ForEach(x => rbEnderecos.Items.Add(new ListItem(  x.end_nom_logradouro + ", " + 
                                                                    x.end_num_endereco + ", " +
                                                                    x.end_nom_cidade + " - " +
                                                                    x.end_sig_uf, 
                                                                    x.end_idt_endereco.ToString())));
            rbEnderecos.Items.Add(new ListItem("Novo Endereço", "0"));
            rbEnderecos.SelectedIndex = 0;

            ddUf.DataValueField = "Key";
            ddUf.DataTextField = "Value";
            ddUf.DataSource = UfModel.Instance.Listar();
            ddUf.DataBind();

            if (lista.Count > 0)
                this.PreencherForm(lista[0]);
            else
            {
                this.HabilitarForm();
                this.LimparForm();
                RegistrarScript();
            }
            
        }

        private void PreencherForm(tb_end_endereco endereco)
        {
            ddUf.ClearSelection();
            txtBairro.Text = endereco.end_des_bairro;
            txtCep.Text = endereco.end_num_cep;
            txtCidade.Text = endereco.end_nom_cidade;
            txtComplemento.Text = endereco.end_des_complemento;
            txtEndereco.Text = endereco.end_nom_logradouro;
            txtNumero.Text = endereco.end_num_endereco.ToString();
            ddUf.Items.FindByValue(endereco.end_sig_uf).Selected = true;
        }

        private void DesabilitarForm()
        {
            txtBairro.ReadOnly = true;
            txtCep.ReadOnly = true;
            txtCidade.ReadOnly = true;
            txtComplemento.ReadOnly = true;
            txtEndereco.ReadOnly = true;
            txtNumero.ReadOnly = true;
            ddUf.Enabled = false;
            btnAdicionarItem.Visible = false;
            btnProsseguir.Visible = true;
        }

        private void HabilitarForm()
        {
            txtBairro.ReadOnly = false;
            txtCep.ReadOnly = false;
            txtCidade.ReadOnly = false;
            txtComplemento.ReadOnly = false;
            txtEndereco.ReadOnly = false;
            txtNumero.ReadOnly = false;
            ddUf.Enabled = true;
            btnAdicionarItem.Visible = true;
            btnProsseguir.Visible = false;
        }

        private void LimparForm()
        {
            txtBairro.Text = string.Empty;
            txtCep.Text = string.Empty;
            txtCidade.Text = string.Empty;
            txtComplemento.Text = string.Empty;
            txtEndereco.Text = string.Empty;
            txtNumero.Text = string.Empty;
            ddUf.SelectedIndex = 0;
        }

        protected void rbEnderecos_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rbEnderecos.SelectedValue.Equals("0"))
            {
                this.HabilitarForm();
                this.LimparForm();
            }
            else
            {
                this.LimparForm();
                this.PreencherForm(EnderecoModel.Instance.Obter(int.Parse(rbEnderecos.SelectedValue)));
                this.DesabilitarForm();
            }
            this.RegistrarScript();
        }

        private void RegistrarScript()
        {
            ClientScript.RegisterStartupScript(this.GetType(), "scripts", "$(document).ready(function () { $('#txtNumero').mask('9?99999', { placeholder: \" \" }); $('#txtCep').mask('99999-999', { placeholder: \" \" }); });", true);
        }

        protected void btnProsseguir_Click(object sender, EventArgs e)
        {
            this.ProsseguirCompra();
        }

        protected void lbProsseguir_Click(object sender, EventArgs e)
        {
            this.ProsseguirCompra();
        }

        private void ProsseguirCompra()
        {
            if (rbEnderecos.SelectedValue.Equals("0"))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "msg", "$(document).ready(function () { alert('Selecione um endereço'); $('#txtNumero').mask('9?99999', { placeholder: \" \" }); $('#txtCep').mask('99999-999', { placeholder: \" \" }); });", true);
            }
            else
            {
                Carrinho.Instance.IdentificadorEndereco = int.Parse(rbEnderecos.SelectedValue);
                Carrinho.Instance.Frete = Direct.Instance.Calcular(txtCep.Text.Replace("-", ""), Carrinho.Instance.PesoTotalKg, Carrinho.Instance.Total);
                Response.Redirect("~/FormaPagamento.aspx");
            }
        }

        protected void btnAdicionarItem_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                tb_end_endereco endereco = new tb_end_endereco();
                endereco.end_dat_criacao = DateTime.Now;
                endereco.end_des_bairro = txtBairro.Text.Trim();
                endereco.end_des_complemento = txtComplemento.Text.Trim();
                endereco.end_nom_cidade = txtCidade.Text.Trim();
                endereco.end_nom_logradouro = txtEndereco.Text.Trim();
                endereco.end_num_cep = txtCep.Text.Trim().Replace("-", "");
                endereco.end_num_endereco = int.Parse(txtNumero.Text);
                endereco.end_sig_uf = ddUf.SelectedValue;
                endereco.pes_idt_pessoa = this.IdentificadorUsuarioLogado;
                endereco.ten_idt_tipo_endereco = 1;

                EnderecoModel.Instance.Inserir(endereco);

                this.CarregarEnderecos();
                DesabilitarForm();
            }
            this.RegistrarScript();
        }
    }
}